<!-- 医院端 - 新建订单 - 新建退货订单 -->
<template>
  <div class="newReturnOrder-box">
    <el-container class="newReturn-box">
      <!-- 头部 -->
      <h3 class="title">基础信息</h3>
      <el-header
        height="auto"
        class="form-wrapper">
        <el-form
          inline
          :rules="rules"
          label-width="130px"
          ref="returnOrderForm"
          :model="returnOrderInfo">
          <!-- 配送商 -->
          <el-form-item
            label="选择配送商"
            prop="deliveryId">
            <el-select
              remote
              filterable
              clearable
              :remote-method="getProviderList"
              @change="handleProviderChange"
              :loading="providerLoading"
              v-model="returnOrderInfo.deliveryId"
              placeholder="请选择">
              <el-option
                v-for="(item, index) in providerList"
                :key="index"
                :label="item.fullName"
                :value="item.companyCode" />
            </el-select>
          </el-form-item>
          <!-- 收货地址 -->
          <el-form-item
            label="选择收货地址"
            prop="addressId">
            <el-select
              clearable
              :disabled="!returnOrderInfo.deliveryId"
              v-model="returnOrderInfo.addressId"
              @visible-change="getAddressList"
              :loading="addressLoading"
              placeholder="请选择">
              <el-option
                :key="index"
                v-for="(item, index) in addressList"
                :label="item.detailedAddress"
                :value="item.id" />
            </el-select>
          </el-form-item>
          <!-- 退货原因 -->
          <el-form-item
            label="输入退货原因"
            prop="remark">
            <el-input
              placeholder="请输入内容"
              v-model="returnOrderInfo.remark"/>
          </el-form-item>
        </el-form>
      </el-header>
      <!-- 列表模块 -->
      <h3 class="title">退货产品</h3>
      <div
        class="top-add-button-wrapper"
        v-if="!isEmptyList">
        <span class="add-button">
          <el-button
            type="text"
            @click="openAddProductDialog">
            添加采购产品
          </el-button>
        </span>
        <span class="order-total-amount">
          总计：{{ formatPrice(orderTotalAmount) }}
        </span>
      </div>
      <el-editable
        v-if="!isEmptyList"
        v-loading="tableLoading"
        :data="curPageList"
        height="400"
        :columns="returnOrderProductListColumns"
      >
        <template
          slot="default-returnNum"
          slot-scope="scope">
          <el-input-number
            v-model="scope.row.returnNum"
            @change="resetIllegalInput(scope.row,$event)"
            size="mini"
            :min="1"
            :max="9999999"
            label="描述文字" />
        </template>
        <template
          slot="default-action"
          slot-scope="scope">
          <el-button
            size="small"
            @click.stop="deleteOrderProductItem(scope)"
            type="text text-danger">删除</el-button>
        </template>
      </el-editable>
      <!-- 分页模块 -->
      <el-pagination
        v-if="!isEmptyList"
        class="pagination"
        align="right"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="curPage"
        :page-sizes="PAGE_NUMBER"
        :page-size="pageSize"
        :layout="PAGINATION_LAYOUT"
        :total="totalElements"
      />
      <div
        class="center-add-button-wrapper"
        v-if="isEmptyList"
      >
        <el-button
          type="primary"
          @click="openAddProductDialog">+ 添加采购产品
        </el-button>
      </div>
      <!-- 添加采购产品 -->
      <add-product-dialog
        title="选择产品"
        type='return'
        query-method="post"
        :query-url="addReturnProduct"
        :extra-query="extraQuery"
        @cancelDialog="cancelAddSelection"
        @confirmDialog="addSelectionToProductList"
        :dialog-visible.sync="addProductDialogShow"
        :current-products="returnOrderProductList" />
    </el-container>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { hospitalList, getAddressListAll,
  createReturn,
  orderDetail,
  getProductList,
  addReturnProduct,
  returnList
} from '@const/beforeSettleApi'
import { computeRate } from '@const/filter'
import { formatPrice } from '@const/agencySaas'
import ElEditable from '@components/el-editable'
import { returnOrderProductListColumns } from './const'

import SearchForm from '@components/businesscomponents/search'
import { PAGE_NUMBER, PAGINATION_LAYOUT } from '@const/common'
import AddProductDialog from '@/moduleComponents/beforeSettle/hospitalSide/addProduct'

export default {
  components: { ElEditable, SearchForm, AddProductDialog },
  data () {
    return {
      addReturnProduct,
      returnOrderProductListColumns, // 页面产品列表表头
      orderDetail: {},
      addProductDialogShow: false,
      providerList: [],
      providerLoading: false,
      addressList: [],
      addressLoading: false,
      returnOrderInfo: {
        deliveryId: '',
        deliveryName: '',
        addressId: '',
        remark: '',
        itemForms: []
      },
      returnOrderProductList: [],
      rules: {
        deliveryId: [{ required: true, message: '请选择', trigger: 'change' }],
        addressId: [{ required: true, message: '请选择', trigger: 'change' }]
      },
      tableLoading: false, // 这里的loading只有在扩展编辑订单功能之后才有用
      curPage: 1,
      PAGE_NUMBER,
      PAGINATION_LAYOUT,
      pageSize: PAGE_NUMBER[0]
    }
  },
  computed: {
    ...mapState(['companyId', 'companyType', 'roleType']),
    id () {
      return this.$route.query.id
    },
    isEdit () {
      return this.$route.query.type === 'edit'
    },
    isEmptyList () {
      return this.returnOrderProductList.length === 0
    },
    // 计算订单总价
    orderTotalAmount () {
      return this.returnOrderProductList.reduce((amount, cur) => amount + computeRate(cur.returnNum, cur.buyPrice), 0)
    },
    curPageList () { // 当前页项
      const startIndex = this.pageSize * (this.curPage - 1)
      const endIndex = startIndex + this.pageSize
      return this.returnOrderProductList.slice(startIndex, endIndex)
    },
    totalElements () {
      return this.returnOrderProductList.length
    },
    orderBaseInfo () {
      return this.orderDetail.odcPurchaseOrderVO || {}
    },
    hasEmptyReturnNum () {
      return this.returnOrderProductList.some(item => !item.returnNum)
    },
    extraQuery () {
      return {
        deliveryCompanyId: this.returnOrderInfo.deliveryId
      }
    }
  },
  watch: {
    id: {
      handler (id) {
        id && this.initDetailInterface()
      },
      immediate: true
    }
  },
  mounted () {
    let obj = {
      type: 'btn',
      arr: [{ type: 'primary', val: '提交', handle: this.handleSubmit }]
    }
    this.$store.commit('changeLayoutHandle', obj)
  },
  methods: {
    formatPrice,
    // 编辑时，查询详情接口
    initDetailInterface () {
      this.getOrderDetail()
      this.getProductList()
    },
    // 获取订单详情
    getOrderDetail () {
      this.$axios.$post(returnList, { id: this.id })
        .then(({ code, payload }) => {
          if (!Object.is(code, '0')) return
          const content = (payload.content && payload.content[0]) || {}
          this.returnOrderInfo.deliveryName = content.deliveryName
          this.returnOrderInfo.deliveryId = content.deliveryId
          this.returnOrderInfo.addressId = content.addressId
          this.returnOrderInfo.remark = content.remark
          this.getProviderList()
          this.getAddressList()
        })
    },
    // 获取产品列表
    getProductList () {
      this.tableLoading = true
      this.$axios.$post(getProductList, { id: this.id })
        .then(({ code, payload }) => {
          if (!Object.is(code, '0')) return
          this.returnOrderProductList = payload.content || []
        })
        .finally(() => { this.tableLoading = false })
    },
    // 查询配送商列表
    getProviderList (companyName = this.returnOrderInfo.deliveryName || '') {
      this.providerLoading = true
      this.$axios.$get(hospitalList, { params: { companyType: 'AG', companyName } })
        .then(({ code, payload }) => {
          if (Number(code)) return
          this.providerList = payload
        })
        .finally(() => {
          this.providerLoading = false
        })
    },
    handleProviderChange (value) {
      // 如果选择的供应商发生了变化，就清空地址
      this.resetAddress()
      // 根据选择的供应商id将供应商名称也存储至订单数据中，因创建订单接口需要
      this.setProviderName(value)
    },
    resetAddress () {
      this.addressList = []
      this.returnOrderInfo.addressId = ''
    },
    setProviderName (value) {
      this.returnOrderInfo.deliveryName = this.providerList.find(item => Object.is(item.companyCode, value)).fullName
    },
    getAddressList () {
      if (this.addressList.length) return
      this.addressLoading = true
      this.$axios.$post(getAddressListAll, { yp: 1 })
        .then(({ code, payload }) => {
          if (!Object.is(code, '0')) return
          const content = payload.content || []
          this.addressList = content.filter(item => item.detailedAddress) // 如果地址列表里warehouseAddress不存在或为空就不显示这条
        })
        .finally(() => {
          this.addressLoading = false
        })
    },
    resetIllegalInput (row, value) {
      if (value % 1 !== 0) {
        row.returnNum = Math.round(value)
      }
    },
    openAddProductDialog () {
      if (!this.returnOrderInfo.deliveryId) {
        this.$message.warning('请先选择供应商！')
        return
      }
      this.addProductDialogShow = true
    },

    addSelectionToProductList (selection) {
      // 如果选择项中已经添加过了，就按最新的数量更新, 未添加过就格式化一下字段添加
      // todo 如果页面中已经添加了，但在弹窗中又取消了选中怎么处理？
      selection.forEach(item => {
        const addedItem = this.returnOrderProductList.find(addedItem => Object.is(addedItem.id, item.id))
        if (addedItem) {
          addedItem.returnNum = item.returnNum
        } else {
          this.returnOrderProductList.push(item)
        }
      })
      this.addProductDialogShow = false
    },

    cancelAddSelection () {
      this.addProductDialogShow = false
    },

    deleteOrderProductItem (row) {
      this.returnOrderProductList.splice(row.$index, 1)
    },

    handleSubmit () {
      this.createReturnOrder(this.isEdit ? this.id : null)
    },
    // 兼容新建和修改，修复时，传id作为标志
    createReturnOrder (id) {
      this.$refs.returnOrderForm.validate(valid => {
        if (valid) {
          if (this.isEmptyList || this.hasEmptyReturnNum) {
            this.$message.warning(this.isEmptyList ? '请添加采购产品' : '采购数量不能为空')
            return
          }
          const itemForms = this.returnOrderProductList.map(item => {
            return { orderItemId: id ? item.orderItemId : item.id, returnNum: item.returnNum }
          })
          let body = { ...this.returnOrderInfo, itemForms }
          id && (body.id = id)
          this.$axios.$post(createReturn, body)
            .then(({ code }) => {
              if (Object.is(code, '0')) {
                this.$message.success('操作成功')
                this.$router.push('/hospitalSide/returnOrderManage/purchaseReturnList')
              }
            })
        }
      })
    },
    handleSizeChange (size) {
      this.pageSize = size
    },
    handleCurrentChange (page) {
      this.curPage = page
    }
  }
}
</script>

<style lang='less'>
.newReturnOrder-box {
  .newReturn-box {
    height: 100%;
    overflow: auto;

    .form-wrapper {
      margin-top: 16px;
      margin-left: -56px;
    }

    .title {
      border-bottom: 1px solid #eee;
      padding-bottom: 10px;
    }

    .top-add-button-wrapper {
      display: flex;
      margin: 24px 0;

      .add-button {
        flex: 1;
      }

      .order-total-amount {
        font-size: 16px;
        font-weight: 500;
      }
    }

    .center-add-button-wrapper {
      flex: 1;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .edit-form {
      .btnBox {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        // background: pink;
        height: 50px;
      }

      .pagination {
        padding-top: 10px;
        display: flex;
        justify-content: flex-end;
        padding-right: 0;
      }
    }

    .ul-list {
      overflow: hidden;
      margin: 10px 0;

      li {
        list-style: none;
        float: left;
        margin-right: 30px;

        i {
          display: inline-block;
          width: 15px;
          height: 10px;
        }

        .auth {
          background: #e6a23c;
        }

        .part {
          background: #eee;
        }
      }
    }
  }
}
</style>
